#
# "@(#) $Id: ArtworkView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from qt import *
from kdeui import KIconView
from kdecore import i18n
#from ArtworkWindow import *
import Utils.amazon,os
from Utils.utils import unikode
from Utils.Paths import art
from ArtworkWindow import *
import time


class ArtworkView(QWidget):

	_validExtensions = ['.jpg','.png']

	def __init__(self,container,name,parent,track=None,writeToFile=True):
		QWidget.__init__(self,container,name)
		#self.imgDrag=QImageDrag(self,'dragimg')
		self.setAcceptDrops(True)
		self.parent = parent
		self.container=container
		self.fullPixmap = None
		self.smallPixmap = None
		self.hasImage = False
		self.currentScale = 0
		self.setPaletteBackgroundColor(QColor(255,255,255))
		self.setBackgroundMode(Qt.NoBackground)
		self.setSizePolicy(QSizePolicy(QSizePolicy.Preferred,QSizePolicy.Preferred,True))
		self.track=track
		self.writeToFile=writeToFile
		self.cap=False
		self.default=False

	#
	# force us to be square up to half the height of our parent
	#
	def heightForWidth(self,w):
		parentMiddle = self.parent.height()/2
		if w>parentMiddle:
			return parentMiddle
		return w

	#
	# recompute the small pixmap as we resize
	#
	def resizeEvent(self,e):
		QWidget.resizeEvent(self,e)
		self.buildSmallPixmap()

	def getArtCap(self):
		return self.cap
		
	def artCap(self,item):
		if item==None:
			return
		self.track=item.track()
		if self.track.kind== 'MPEG audio file' or self.track.kind=='MPEG-4 audio file':
			self.cap=True
			if self.isVisible():
				self.fetchItemArtwork()
		else:
			self.cap=False
	
	def putArtCap(self,cap):
		self.cap=cap
		
	#
	# get the song's artwork and build a scaled version for quicker drawing
	#
	def fetchItemArtwork(self):		
		data = self.track.getImage()
		if data != None:
			self.fullPixmap = QPixmap()
			self.fullPixmap.loadFromData(data)
			self.currentScale = 0
			self.buildSmallPixmap()
			self.hasImage = True
			self.setEnabled(True)
			self.default=False
			#self.fullPixmap.setDragEnabled(True)
		else:
			self.setDefault()
		
		#self.imgDrag.setImage(self.smallPixmap.convertToImage())


	def setImg(self,image):
		if image != None:
			self.fullPixmap = image
			#self.fullPixmap.loadFromData(image)
			self.currentScale = 0
			self.buildSmallPixmap()
			self.hasImage = True
			self.setEnabled(True)
			self.default=False
		else:
			self.setDefault()
		remBtn=self.parent.child('remBtn')
		remBtn.setEnabled(True)
			
	def setDefault(self):
		if self.default!=True:
			self.fullPixmap = QPixmap(art('artwork.png'))
			self.buildSmallPixmap()
			self.default=True
	#
	# build a scaled version of the full sized image and keep it
	# maintain the aspect ratio, and don't increase the size
	#
	def buildSmallPixmap(self):
		if self.fullPixmap:
			pixSize = self.fullPixmap.size()
			size = self.size()
			width = pixSize.width()
			height = pixSize.height()
			if width==0: width = 1
			if height==0: height = 1
			scaleX = 1.0*size.width()/width
			scaleY = 1.0*size.height()/height
			scale = scaleX
			if scaleX>scaleY:
				scale = scaleY
			if scale>1.0:
				scale = 1.0
			if scale != self.currentScale:
				mat = QWMatrix()
				mat.scale(scale,scale)
				self.smallPixmap = self.fullPixmap.xForm(mat)
				self.currentScale = scale
		else:
			self.smallPixmap = QPixmap()
		self.repaint()

	#
	# paint the cached scaled image of the cover in the artwork area
	#
	# to avoid flicker, we've turned off erasing, so we're responsible for
	# clearing out the emptry areas around the picture
	#
	def paintEvent(self,e):
		p = QPainter()
		p.begin(self)
		p.setBrush(QColor(255,255,255))
		p.setPen(QColor(255,255,255))
		srcSize = self.smallPixmap.size()
		dstSize = self.size()
		posX = (dstSize.width()-srcSize.width())/2
		posY = (dstSize.height()-srcSize.height())/2
		bitBlt(self,QPoint(posX,posY),self.smallPixmap,self.smallPixmap.rect(),Qt.CopyROP)
		if posX:
			r = QRect(0,0,posX,dstSize.height())
			p.drawRect(r)
			r = QRect(dstSize.width()-posX,0,posX,dstSize.height())
			p.drawRect(r)
		if posY:
			r = QRect(0,0,dstSize.width(),posY)
			p.drawRect(r)
			r = QRect(0,dstSize.height()-posY,dstSize.width(),posY)
			p.drawRect(r)
		p.end()

	def mouseDoubleClickEvent(self,ev):
		if not self.default:
			self.openInWindow()
	
	def openInWindow(self):
		self.art = ArtworkWindow(self.fullPixmap,self.track.title)

	def dragEnterEvent(self,event):
		print "drag enter"
		if QUriDrag.canDecode(event):
			uris = QStringList()
			if QUriDrag.decodeLocalFiles(event,uris):
				if self.canImportFiles(uris):
					event.accept(True)

	def dropEvent(self,event):
		print "dropped remote drag on art"
		uris = QStringList()
		if QUriDrag.decodeLocalFiles(event,uris):
			for uri in uris:
				if self.writeToFile:
					f=open(str(uri))
					self.track.image=f.read()
					f.close()
					data=self.track.image
					if data != None:
						self.fullPixmap = QPixmap()
						self.fullPixmap.loadFromData(data)
						self.currentScale = 0
						self.buildSmallPixmap()
						self.hasImage = True
						self.setEnabled(True)
						self.default=False
				else:
					self.setImg(QPixmap(str(uri)))
				#self.parent.deleteButton.setEnabled(True)
				break
					
		
	def canImportFile(self,filePath):
		if os.path.exists(str(filePath)):
			if os.path.isdir(str(filePath)):
				return False
			else:
				ext = os.path.splitext(str(filePath))[1]
				if ext in self._validExtensions:
					return True
		return False

	def canImportFiles(self,uris):
		for uri in uris:
			if self.canImportFile(uri):
				return True
		return False
